// File Name: init.c
// Author: kukukukuku~
// Date: 2024-12-20

#include "apm32f00x_fmc.h"
#include "apm32f00x_rcm.h"
#include "./Key/inc/key_task.h"
#include "./LED/inc/led_interface.h"
#include "./OLED/inc/oled_task.h"
#include "./RS485/inc/rs485_task.h"
#include "./Sys/inc/init.h"
#include "./USART/inc/usart_task.h"

/**
 * @brief   系统时钟配置
 * @param   None
 * @retval  None
 * @note    静态
*/
static void rcm_config(void)
{
    RCM_SwitchClockStruct_T rcmSwitchClkStruct = 
    {
        .currentClkState = RCM_CLOCK_STATE_OFF,
        .intEnable       = DISABLE,
        .clockSource     = RCM_MCLKSRC_HIRC,
        .mode            = RCM_SWITCH_MODE_AUTO,
    };
    
    //内部高速时钟1分频 48MHz
    RCM_ConfigHIRCDiv(RCM_HIRC_DIV_1);
    //切换时钟
    RCM_ConfigClockSwitch(&rcmSwitchClkStruct);

    //设置FLASH读写等待1个周期
    FMC_SetLatency(FMC_LATENCY_1);
}


/**
 * @brief   初始化任务
 * @param   arg:    任务参数
 * @retval  None
 * @note    None
*/
void init_task(void *arg)
{
    taskENTER_CRITICAL();
    
    xTaskCreate(key_task, KEY_TASK_LABEL, KEY_TASK_STACK, NULL, KEY_TASK_PRIORITIES, &keyTaskHandle);
    xTaskCreate(oled_task, OLED_TASK_LABEL, OLED_TASK_STACK, NULL, OLED_TASK_PRIORITIES, &oledTaskHandle);
    xTaskCreate(rs485_task, RS485_TASK_LABEL, RS485_TASK_STACK, NULL, RS485_TASK_PRIORITIES, &rs485TaskHandle);
    xTaskCreate(usart_task, USART_TASK_LABEL, USART_TASK_STACK, NULL, USART_TASK_PRIORITIES, &usartTaskHandle);
    
    taskEXIT_CRITICAL();
    
    vTaskDelete(NULL);
}


/**
 * @brief   系统初始化
 * @param   None
 * @retval  None
 * @note    None
*/
void system_init(void)
{
    rcm_config();
    
    key_init();
    led_init();
    oled_init();
    rs485_init();
    usart_init();
}
